#!/bin/bash

master_home=/home/cluster/master/
node_home=/home/cluster/node/
action_list=action_list.txt
job_list=job_list.txt

###############################命令输入###################################

if [ $# -gt 2 ]
then
  echo 'command like "action [-add /-a] or [-terminate /-t] or [-state /-s] [path]"'
  exit
fi

if [ $# -eq 2 ]
then
para2=`echo $2 |sed 's#/$##'`
  if [[ $1 = '-a' && -d $para2 ]]
  then
    para1="ADD"
  elif [[ $1 = '-t' && -d $para2 ]]
  then
    para1="TERMINATE"
  elif [[ $1 = '-s' && -d $para2 ]]
  then
    para1="STATE"
  else
    echo 'command like "action [-add /-a] or [-terminate /-t] or [-state /-s] [path]"'
    exit
  fi


elif [ $# -eq 1 ]
then 

  if [ $1 = '-a' ]
  then 
    para1="ADD"
    para2=`pwd`
  elif [ $1 = '-t' ]
  then
    para1="TERMINATE"
    para2=`pwd`
  elif [ $1 = '-s' ]
  then 
    para1="STATE"
    para2=`pwd`
  elif [ -d $1 ]
  then
    para1="ADD"
    para2=$1
  else
    echo 'action [-add /-a] or [-terminate /-t] or [-state /-s] [path]"'
    exit
  fi

else
  para1="ADD"
  para2=`pwd`

fi

######################################命令处理###################################

if [ $para1 = "STATE" ]
then
    exist=`grep "ADD.* $para2 " $master_home$action_list `
    if [ "$exist" ]
    then 
      echo "state:ADD"
      exit
    fi

    exist=`grep " $para2 " $master_home$job_list `
    if [ "$exist" ]
    then 
      exist=( $exist )
      echo "state:RUNNING on ${exist[3]} , route: $node_home${exist[0]}/ "
      exit
    fi
    echo "job is not in the system or had complete!"
    exit
fi

if [ $para1 = "TERMINATE" ]
then
exist1=`grep "ADD.* $para2 " $master_home$action_list `
exist2=`grep " $para2 " $master_home$job_list `  #在joblist中查找是否已存在该任务

    if [ "$exist1" ]
    then
      para1=`echo $para2 | sed 's#/#\\\/#g'` #转义
      sed -i "/ $para1 /"d $master_home$action_list
      echo "terminate job done!"
    elif [ "$exist2" ]
    then

      job_=( `grep " $para2 " $master_home$job_list` )
      if [ "$job_" ]
      then
	ssh ${job_[3]} "kill ${job_[4]} && rm -R $node_home${job_[0]}"
	sed -i "/^${job_[0]}/"d $master_home$job_list
	echo "terminate job done!"
      fi
    else
      echo "the job is not runing!"
    fi
    exit
fi


if [[ $para1 = "ADD" && -f $para2/main.sh ]]
then
exist1=`grep "ADD.* $para2 " $master_home$action_list `
exist2=`grep " $para2 " $master_home$job_list `  #在joblist中查找是否已存在该任务
    if [[ "$exist1" || "$exist2" ]]
    then
      echo "the job had already been added to the system or is waiting to be terminated!"
    else
      echo "$para1  $para2 " >> $master_home$action_list
      echo "add job done!"
    fi
else
  echo "there is no main.sh!"
fi
